/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaEditorDeTemas.java
 *
 * Created on Jun 1, 2011, 9:25:02 PM
 */
package cataletra.gui;

import cataletra.main.Mascara;
import cataletra.db.DB;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author arthur
 */
public class JanelaEditorDeTemas extends javax.swing.JDialog {
    
    private DB db;
    
    /** Creates new form JanelaEditorDeTemas */
    public JanelaEditorDeTemas(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        this.setLocationRelativeTo(parent);
        
        db = new DB();
        reiniciar(true);
        
        campoNovoTema.setDocument(new Mascara(50, true, false));
        campoPalavra.setDocument(new Mascara(20, false, false));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        painelAbas = new javax.swing.JTabbedPane();
        painelAdicionar = new javax.swing.JPanel();
        labelPalavraAdicionar = new javax.swing.JLabel();
        campoPalavra = new javax.swing.JTextField();
        botaoAdicionar = new javax.swing.JButton();
        comboTemasAdicionar = new javax.swing.JComboBox();
        campoNovoTema = new javax.swing.JTextField();
        labelTemaAdicionar = new javax.swing.JLabel();
        labelNovoTema = new javax.swing.JLabel();
        botaoFecharNovoTema = new javax.swing.JButton();
        labelMensagemAdicionar = new javax.swing.JLabel();
        labelGambiarra2 = new javax.swing.JLabel();
        barraRolagem = new javax.swing.JScrollPane();
        painelPalavras = new javax.swing.JPanel();
        painelRemover = new javax.swing.JPanel();
        labelPalavraRemover = new javax.swing.JLabel();
        comboPalavras = new javax.swing.JComboBox();
        botaoRemover = new javax.swing.JButton();
        labelTemasRemover = new javax.swing.JLabel();
        comboTemasRemover = new javax.swing.JComboBox();
        labelMensagemRemover = new javax.swing.JLabel();
        labelGambiarra1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Editor de Temas");
        setMinimumSize(new java.awt.Dimension(250, 250));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                onClose(evt);
            }
        });

        painelAbas.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                mudarAba(evt);
            }
        });

        painelAdicionar.setLayout(new java.awt.GridBagLayout());

        labelPalavraAdicionar.setText("Palavra");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        painelAdicionar.add(labelPalavraAdicionar, gridBagConstraints);

        campoPalavra.setMinimumSize(new java.awt.Dimension(4, 24));
        campoPalavra.setPreferredSize(new java.awt.Dimension(160, 24));
        campoPalavra.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                campoPalavraKeyTyped(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(3, 5, 5, 5);
        painelAdicionar.add(campoPalavra, gridBagConstraints);

        botaoAdicionar.setText("Adicionar");
        botaoAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoAdicionar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        painelAdicionar.add(botaoAdicionar, gridBagConstraints);

        comboTemasAdicionar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboTemasAdicionar.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                mudarComboTemasAdicionar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(3, 5, 5, 5);
        painelAdicionar.add(comboTemasAdicionar, gridBagConstraints);

        campoNovoTema.setMinimumSize(new java.awt.Dimension(4, 24));
        campoNovoTema.setPreferredSize(new java.awt.Dimension(4, 24));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(3, 5, 5, 5);
        painelAdicionar.add(campoNovoTema, gridBagConstraints);

        labelTemaAdicionar.setText("Tema");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        painelAdicionar.add(labelTemaAdicionar, gridBagConstraints);

        labelNovoTema.setText("Novo Tema");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        painelAdicionar.add(labelNovoTema, gridBagConstraints);

        botaoFecharNovoTema.setText("X");
        botaoFecharNovoTema.setMargin(new java.awt.Insets(0, 0, 0, 0));
        botaoFecharNovoTema.setMaximumSize(new java.awt.Dimension(20, 20));
        botaoFecharNovoTema.setMinimumSize(new java.awt.Dimension(20, 20));
        botaoFecharNovoTema.setPreferredSize(new java.awt.Dimension(20, 20));
        botaoFecharNovoTema.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoFecharNovoTema(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        painelAdicionar.add(botaoFecharNovoTema, gridBagConstraints);

        labelMensagemAdicionar.setText("Digite a palavra");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        painelAdicionar.add(labelMensagemAdicionar, gridBagConstraints);

        labelGambiarra2.setText("_____________________________________");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 7;
        gridBagConstraints.gridwidth = 2;
        painelAdicionar.add(labelGambiarra2, gridBagConstraints);

        painelPalavras.setLayout(new java.awt.GridLayout(1, 2));
        barraRolagem.setViewportView(painelPalavras);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        painelAdicionar.add(barraRolagem, gridBagConstraints);

        painelAbas.addTab("Adicionar", painelAdicionar);

        painelRemover.setLayout(new java.awt.GridBagLayout());

        labelPalavraRemover.setText("Palavra");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        painelRemover.add(labelPalavraRemover, gridBagConstraints);

        comboPalavras.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboPalavras.setPreferredSize(new java.awt.Dimension(120, 24));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(3, 5, 5, 5);
        painelRemover.add(comboPalavras, gridBagConstraints);

        botaoRemover.setText("Remover");
        botaoRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoRemover(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        painelRemover.add(botaoRemover, gridBagConstraints);

        labelTemasRemover.setText("Tema");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        painelRemover.add(labelTemasRemover, gridBagConstraints);

        comboTemasRemover.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboTemasRemover.setPreferredSize(new java.awt.Dimension(160, 24));
        comboTemasRemover.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                mudarComboTemasRemover(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(3, 5, 5, 5);
        painelRemover.add(comboTemasRemover, gridBagConstraints);

        labelMensagemRemover.setText("Selecione a palavra");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        painelRemover.add(labelMensagemRemover, gridBagConstraints);

        labelGambiarra1.setText("_____________________________________");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.gridwidth = 2;
        painelRemover.add(labelGambiarra1, gridBagConstraints);

        painelAbas.addTab("Remover", painelRemover);

        getContentPane().add(painelAbas, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mudarComboTemasAdicionar(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_mudarComboTemasAdicionar
        if(comboTemasAdicionar.getSelectedItem().equals("NOVO TEMA")){
            labelTemaAdicionar.setVisible(false);
            comboTemasAdicionar.setVisible(false);
            labelNovoTema.setVisible(true);
            campoNovoTema.setVisible(true);
            botaoFecharNovoTema.setVisible(true);   
            labelMensagemAdicionar.setText("Digite o novo tema");
            barraRolagem.setVisible(false);
            atualizarTamanho(false);
        }
        
        atualizarPainelPalavras();
    }//GEN-LAST:event_mudarComboTemasAdicionar

    private void clicarBotaoRemover(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoRemover
        String tema = (String) comboTemasRemover.getSelectedItem();        
        String palavra = (String) comboPalavras.getSelectedItem();
        
        int resposta = JOptionPane.YES_OPTION;
        if(palavra.equals("Todas")){
            palavra = "";
            String mensagem = "Tem certeza que deseja remover esse tema?\nEssa operação não pode ser desfeita.";
            resposta = JOptionPane.showConfirmDialog(this, mensagem, "Atenção!", JOptionPane.YES_NO_OPTION);
        }
        
        
        if(db.remover(tema, palavra)){
            if(resposta == JOptionPane.YES_OPTION){
                labelMensagemRemover.setText("Removido com sucesso");
                reiniciar(true);                
            }
        } else {
            labelMensagemRemover.setText("Erro ao remover");
        }
    }//GEN-LAST:event_clicarBotaoRemover

    private void clicarBotaoAdicionar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoAdicionar
        String tema;
        
        if(comboTemasAdicionar.getSelectedItem().equals("NOVO TEMA")){
            tema = campoNovoTema.getText();
        } else {
            tema = (String) comboTemasAdicionar.getSelectedItem();
        }
        
        String palavra = campoPalavra.getText();
        
        if(db.inserir(tema, palavra)){
            if(comboTemasAdicionar.getSelectedItem().equals("Novo Tema")){
                labelMensagemAdicionar.setText("Tema inserido com sucesso");
            } else {
                labelMensagemAdicionar.setText("Palavra inserida com sucesso");
            }
        } else {
            labelMensagemAdicionar.setText("Este item ja existe");
        }
        
        reiniciar(true);
        comboTemasAdicionar.setSelectedItem(tema);
    }//GEN-LAST:event_clicarBotaoAdicionar

    private void clicarBotaoFecharNovoTema(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoFecharNovoTema
        comboTemasAdicionar.setSelectedIndex(0);
        labelMensagemAdicionar.setText("Digite a palavra");
        reiniciar(false);
    }//GEN-LAST:event_clicarBotaoFecharNovoTema

    private void mudarComboTemasRemover(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_mudarComboTemasRemover
        atualizarComboPalavras();
    }//GEN-LAST:event_mudarComboTemasRemover

    private void onClose(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_onClose
        try{
            JanelaPrincipal pai = (JanelaPrincipal) this.getParent();
            pai.reiniciar();
        } catch(ClassCastException e){
            
        }
    }//GEN-LAST:event_onClose

    private void mudarAba(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_mudarAba
        if(db != null){
            if(painelAbas.getSelectedIndex() == 0){
                reiniciar(true);
            } else {
                atualizarTamanho(false);
            }
        }
    }//GEN-LAST:event_mudarAba

    private void campoPalavraKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoPalavraKeyTyped
        if(evt.getKeyChar() == KeyEvent.VK_ENTER){
            clicarBotaoAdicionar(null);
        }
    }//GEN-LAST:event_campoPalavraKeyTyped
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JanelaEditorDeTemas dialog = new JanelaEditorDeTemas(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane barraRolagem;
    private javax.swing.JButton botaoAdicionar;
    private javax.swing.JButton botaoFecharNovoTema;
    private javax.swing.JButton botaoRemover;
    private javax.swing.JTextField campoNovoTema;
    private javax.swing.JTextField campoPalavra;
    private javax.swing.JComboBox comboPalavras;
    private javax.swing.JComboBox comboTemasAdicionar;
    private javax.swing.JComboBox comboTemasRemover;
    private javax.swing.JLabel labelGambiarra1;
    private javax.swing.JLabel labelGambiarra2;
    private javax.swing.JLabel labelMensagemAdicionar;
    private javax.swing.JLabel labelMensagemRemover;
    private javax.swing.JLabel labelNovoTema;
    private javax.swing.JLabel labelPalavraAdicionar;
    private javax.swing.JLabel labelPalavraRemover;
    private javax.swing.JLabel labelTemaAdicionar;
    private javax.swing.JLabel labelTemasRemover;
    private javax.swing.JTabbedPane painelAbas;
    private javax.swing.JPanel painelAdicionar;
    private javax.swing.JPanel painelPalavras;
    private javax.swing.JPanel painelRemover;
    // End of variables declaration//GEN-END:variables

        
    private void reiniciar(boolean recarregarTemas){
        labelTemaAdicionar.setVisible(true);
        comboTemasAdicionar.setVisible(true);
        botaoRemover.setEnabled(true);
        labelNovoTema.setVisible(false);
        campoNovoTema.setVisible(false);
        botaoFecharNovoTema.setVisible(false);
        
        campoNovoTema.setText("");
        campoPalavra.setText("");
        
        if(recarregarTemas){
            Object[] temas = db.getTemas();
            Object[] listaTemas = new Object[temas.length + 1];        
            System.arraycopy(temas, 0, listaTemas, 0, temas.length); //copia os dados de tema para listaTemas
            listaTemas[listaTemas.length - 1] = "NOVO TEMA";

            comboTemasRemover.setModel(new DefaultComboBoxModel(temas));
            comboTemasAdicionar.setModel(new DefaultComboBoxModel(listaTemas));
            
            atualizarComboPalavras();
            atualizarPainelPalavras();
        }           
        
        mudarComboTemasAdicionar(null);
    }
    
    
    private void atualizarPainelPalavras(){
        String tema = (String) comboTemasAdicionar.getSelectedItem();
        
        if(tema.equals("NOVO TEMA")){
            barraRolagem.setVisible(false);
            atualizarTamanho(false);
            return;
        } else {
            barraRolagem.setVisible(true);
        }
        
        Object[] palavras = db.getPalavras(tema);        
        int qtdePalavras = palavras.length;
        
        int linhas;
        if(qtdePalavras % 2 == 0){            //se a qtde de palavras for par, a metade é inteira
            linhas = qtdePalavras / 2;
        } else {                                 //se for impar, arredonde a metade pra cima.
            linhas = (qtdePalavras / 2) + 1;
        }
        
        if(linhas < 8){
            barraRolagem.setSize(new Dimension(0, 27 * linhas + 7));
            barraRolagem.setPreferredSize(new Dimension(0, 27 * linhas + 7));
            barraRolagem.setMinimumSize(new Dimension(0, 27 * linhas + 7));
        } else {
            barraRolagem.setSize(new Dimension(0, 25 * 8 + 7));
            barraRolagem.setMinimumSize(new Dimension(0, 25 * 8 + 7));
            barraRolagem.setPreferredSize(new Dimension(0, 25 * 8 + 7));
        }

        atualizarTamanho(true);
        
        GridLayout gridLayout = new GridLayout(linhas, 2, 10, 15);

        painelPalavras.removeAll();
        painelPalavras.setLayout(gridLayout);
        Font fonte = new Font("Tahoma", Font.PLAIN, 12);

        ArrayList labels = new ArrayList();
        for(int i = 0; i < qtdePalavras; i++){
            String p = (String) palavras[i];
            JLabel label = new JLabel(p.toUpperCase());
            label.setFont(fonte);
            label.setHorizontalAlignment(JLabel.CENTER);
            labels.add(label);
            painelPalavras.add(label);
        }
        
        painelAbas.updateUI();
    }
    
    
    private void atualizarComboPalavras(){
        Object[] palavras = db.getPalavras((String) comboTemasRemover.getSelectedItem());
        Object[] listaPalavras = new Object[palavras.length + 1];
        listaPalavras[0] = "TODAS";
        System.arraycopy(palavras, 0, listaPalavras, 1, palavras.length); //copia os dados de palavras para listaPalavras

        comboPalavras.setModel(new DefaultComboBoxModel(listaPalavras));
    }
    
    private void atualizarTamanho(boolean usarBarraDeRolagem){
        int tamanhoJanela = 250;
        
        if(usarBarraDeRolagem){
            tamanhoJanela += barraRolagem.getSize().getHeight();
        }
        
        this.setSize(new Dimension((int)this.getSize().getWidth(), tamanhoJanela));
        this.setPreferredSize(new Dimension((int)this.getSize().getWidth(), tamanhoJanela));
        this.setMinimumSize(new Dimension((int)this.getSize().getWidth(), tamanhoJanela));
        this.setMaximumSize(new Dimension((int)this.getSize().getWidth(), tamanhoJanela));
    }
}
